package com.java.shop.interceptor;

import com.java.shop.code.CommonConst;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截器了");
        boolean flag = false;
        String url = request.getRequestURI();
        System.out.println("----- url："+url);
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        System.out.println("----- username："+username);
        if(StringUtils.isEmpty(username) ) {
            if("/".equals(url)){
                Cookie cookie = new Cookie("username","");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                cookie = new Cookie("photo","");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
                flag = true;
            }else{
                flag = false;
            }
        }else{
            //重置session过期时间
            session.setMaxInactiveInterval(CommonConst.SESSION_OUT_TIME);
            flag = true;
        }
        System.out.println("拦截器拦截结果："+flag+" (false：拦截不向下执行，true：不拦截继续向下执行)");
        if(!flag){
            response.sendRedirect(request.getContextPath());
        }
        return flag;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
